import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';

import {requestLogin,requestUserInfo,requestLogout} from '@/api/userInfo'
import type {reqLoginParamType,reqUserInfoReturnType} from '@/api/userInfo'

import {staticRoutes} from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export interface UserInfoState{
  token:string;
  //userInfo的值是请求回来的,所以类型直接设置为请求的返回值类型
  userInfo:reqUserInfoReturnType;
  menuRoutes:RouteRecordRaw[]
}
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: staticRoutes
  }),

	actions: {
  async  login (loginParam: reqLoginParamType) {
     try{
      const result=await requestLogin(loginParam)
      //拿到结果token设置给state中
      this.token=result.token;
       //设置自动登录(持久化保存token)
       setToken(this.token)
     } catch(e){
      return Promise.reject(e)
     }
    },

     //用户信息请求的方法
  async  getInfo () {
     
     try{
       //发送用户信息请求
       const result=await requestUserInfo();
      //  把数据交给state
      this.userInfo=result
     } catch(e){
      return Promise.reject(e)
     }
    },
 //退出登录的方法
 async getLogout(){
  try{
     //发送退出登录请求
     await requestLogout();
    //  做出清理工作
    this.reset();
  } catch(e){
    return Promise.reject(e)
  }
 },
    reset () {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.userInfo={
        routes: [],
        buttons: [],
        roles: [],
        name: "",
        avatar: "",
      }
    },
	},
});
